package com.xiaoxin.experience.service.net;

import com.sun.management.OperatingSystemMXBean;
import com.xiaoxin.experience.service.net.model.SystemInfo;
import com.xiaoxin.experience.util.*;
import sun.management.ManagementFactoryHelper;

import java.lang.management.RuntimeMXBean;

/**
 * @author xiaoxin
 */
public class SystemMonitor
{
    public synchronized static SystemInfo getSystemInfo()
    {
        SystemInfo systemInfo = new SystemInfo();
        OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactoryHelper.getOperatingSystemMXBean();
        String arch = operatingSystemMXBean.getArch();
        systemInfo.setArch(arch);
        String name = operatingSystemMXBean.getName();
        systemInfo.setName(name);
        String version = operatingSystemMXBean.getVersion();
        systemInfo.setVersion(version);

        long freePhysicalMemorySize = operatingSystemMXBean.getFreePhysicalMemorySize();
        systemInfo.setFreePhysicalMemorySize(FileUtil.getHumanFileSize(freePhysicalMemorySize));
        long totalPhysicalMemorySize = operatingSystemMXBean.getTotalPhysicalMemorySize();
        systemInfo.setTotalPhysicalMemorySize(FileUtil.getHumanFileSize(totalPhysicalMemorySize));
        systemInfo.setPhysicalMemoryUsedPercent(StringUtil.floatFormat(((totalPhysicalMemorySize-freePhysicalMemorySize)*100.0)/totalPhysicalMemorySize) + "%");

        long freeSwapSpaceSize = operatingSystemMXBean.getFreeSwapSpaceSize();
        systemInfo.setFreeSwapSpaceSize(FileUtil.getHumanFileSize(freeSwapSpaceSize));
        long totalSwapSpaceSize = operatingSystemMXBean.getTotalSwapSpaceSize();
        systemInfo.setTotalSwapSpaceSize(FileUtil.getHumanFileSize(totalSwapSpaceSize));
        systemInfo.setSwapSpaceUsedPercent(StringUtil.floatFormat(((totalSwapSpaceSize-freeSwapSpaceSize)*100.0)/totalSwapSpaceSize) + "%");

        RuntimeMXBean runtimeMXBean = ManagementFactoryHelper.getRuntimeMXBean();
        systemInfo.setPid(runtimeMXBean.getName().split("@")[0]);
        systemInfo.setProcessStartTime(DateUtil.formatTimeStd(runtimeMXBean.getStartTime()));
        systemInfo.setProcessRunTime(TimeUtil.getHumanTime(runtimeMXBean.getUptime()));
        return systemInfo;
    }
}
